import { Content, Header } from '@/components/Page';
import { FC, useEffect } from 'react';
import axios from 'axios';

const MyFile: FC = () => {
  const generateBlob = () => {
    const obj = { key: 'value' };
    const blob = new Blob([JSON.stringify(obj)], { type: 'application/json' });
    console.log('blob:', blob);
  };

  const generateFile = () => {
    const fileContent = 'my_file_contents'; // 文件内容
    const fileName = '测试.txt'; // 文件名
    const file = new File([fileContent], fileName);
    console.log('file:', file);
  };

  const generateFormData = () => {
    const formData = new FormData();
    formData.append('name', 'lzx');
    formData.append('age', '24');
    formData.set('name', '6');
    formData.append('sex', '男');
    formData.delete('sex');
    console.log('formData:', formData);
    formData.forEach((value, key) => console.log(key, value));
  };

  const handleSliceUpload = () => {
    const fileContent = 'abc_def_hig';
    // 文件对象
    const file = new File([fileContent], 'test.txt');
    // 每一片的大小
    const chunkSize = 4;
    for (let i = 0; i < file.size; i += chunkSize) {
      // 分片
      const chunk = file.slice(i, i + chunkSize);
      console.log(chunk);
      // 构造请求体
      const uploadData = new FormData();
      uploadData.append('chunkData', chunk);
      uploadData.append('uid', '同一个文件的唯一ID');
      // 发送请求
      axios.post('xxx', uploadData);
    }
  };

  useEffect(() => {
    generateBlob();
    generateFile();
    generateFormData();
    handleSliceUpload();
  }, []);

  return (
    <>
      <Header title="文件流相关" backPath="/test-pages" />
      <Content>文件流相关</Content>
    </>
  );
};

export default MyFile;
